<?php

namespace App\Http\Controllers;

use App\Goods;
use App\GoodsAttrValue;
use App\GoodsCategory;
use Illuminate\Http\Request;
use Illuminate\Queue\RedisQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GoodsController extends Controller
{
    public $goods_cats;
    protected $wechat;

    public function __construct()
    {
        $goods_category_controller = new GoodsCategoryController();
        $this->goods_cats = $goods_category_controller->getList(GoodsCategory::where('id','!=',9999)->orderBy('sort','asc')->get(), 0, 0);//所有分类列表

        $this->wechat = new WeChatController();
    }

    public function _list(Request $request){
        $cond = [];
        $search_data = [];
        if($request->filled('cat_id')){
            $cond[] = ['cat_id','=',$request->cat_id];
            $search_data['cat_id'] = $request->cat_id;
        }
        if($request->filled('is_new')){
            $cond[] = ['is_new','=',$request->is_new];
            $search_data['is_new'] = $request->is_new;
        }
        if($request->filled('is_hot')){
            $cond[] = ['is_hot','=',$request->is_hot];
            $search_data['is_hot'] = $request->is_hot;
        }
        if($request->filled('is_recommend')){
            $cond[] = ['is_recommend','=',$request->is_recommend];
            $search_data['is_recommend'] = $request->is_recommend;
        }
        if($request->filled('is_onshelf')){
            $cond[] = ['is_onshelf','=',$request->is_onshelf];
            $search_data['is_onshelf'] = $request->is_onshelf;
        }
        if($request->filled('title')){
            $cond[] = ['title','like','%'.$request->title.'%'];
            $search_data['title'] = $request->title;
        }
        $list = Goods::where($cond)
            ->select(
                'goods.id as id',
                'goods.title as title',
                'item_no',
                'goods.img as img',
                'goods_category.name as cat_name',
                'brand.name as brand_name',
                'sell_price',
                'stock',
                'sales_volumn'
            )
            ->leftJoin('goods_category', 'goods.cat_id', '=', 'goods_category.id')
            ->leftJoin('brand', 'goods.brand_id', '=', 'brand.id')
            ->orderBy('goods.sort','asc')
            ->get();
        return view('Goods.list',[
            'cats' => $this->goods_cats,
            'list' => $list,
            'search_data' => $search_data
        ]);
    }

    public function edit(Request $request){
        $id = $request->filled('id') ? $request->id : null;
        $info = $id ? Goods::find($id) : [];

        if(!$_POST){
            $info['attr_values'] = GoodsAttrValue::where('goods_id', $id)->get();
            return view('Goods.edit', [
                'cats' => $this->goods_cats,
                'info' => $info
            ]);
        }

        $title = $request->filled('title') ? $request->title : '';
        $item_no = $request->filled('item_no') ? $request->item_no : '';
        $img = $request->filled('img') ? $request->img : '';
        $cat_id = $request->filled('cat_id') ? $request->cat_id : '';
        $brand_id = $request->filled('brand_id') ? $request->brand_id : '';
        $description = $request->filled('description') ? $request->description : '';
        $keywords = $request->filled('keywords') ? $request->keywords : '';
        $services = $request->filled('services') ? $request->services : '';
        $sell_price = $request->filled('sell_price') ? $request->sell_price : 0;
        $market_price = $request->filled('market_price') ? $request->market_price : 0;
        $cost_price = $request->filled('cost_price') ? $request->cost_price : 0;
        $stock = $request->filled('stock') ? $request->stock : 0;
        $score = $request->filled('score') ? $request->score : 0;
        $is_new = $request->filled('is_new') ? ($request->is_new == 'true' ? true : false) : false;
        $is_hot = $request->filled('is_hot') ? ($request->is_hot == 'true' ? true : false) : false;
        $is_recommend = $request->filled('is_recommend') ? ($request->is_recommend == 'true' ? true : false) : false;
        $is_onshelf = $request->filled('is_onshelf') ? ($request->is_onshelf == 'ture' ? true : false) : true;
        $detail = $request->filled('detail') ? parseUeditorImage($request['detail']) : '';
        $attr_values = $request->filled('attr_values') ? $request->attr_values : [];
        $album = $request->filled('album') ? $request->album : '';

        if($id){
            //update
            Goods::where('id', $id)->update([
                'title' => $title,
                'description' => $description,
                'item_no' => $item_no,
                'img' => $img,
                'album' => $album,
                'keywords' => $keywords,
                'services' => $services,
                'cat_id' => $cat_id,
                'brand_id' => $brand_id,
                'sell_price' => $sell_price,
                'market_price' => $market_price,
                'cost_price' => $cost_price,
                'stock' => $stock,
                'score' => $score,
                'detail' => $detail,
                'is_new' => $is_new,
                'is_hot' => $is_hot,
                'is_recommend' => $is_recommend,
                'is_onshelf' => $is_onshelf,
            ]);
            //删除所有相关属性
            GoodsAttrValue::where('goods_id', $id)->delete();
        }else{
            //add
            $goods = new Goods();
            $goods->title = $title;
            $goods->description = $description;
            $goods->item_no = $item_no;
            $goods->img = $img;
            $goods->album = $album;
            $goods->keywords = $keywords;
            $goods->services = $services;
            $goods->cat_id = $cat_id;
            $goods->brand_id = $brand_id;
            $goods->sell_price = $sell_price;
            $goods->market_price = $market_price;
            $goods->cost_price = $cost_price;
            $goods->stock = $stock;
            $goods->sales_volumn = 0;//销量
            $goods->score = $score;
            $goods->detail = $detail;
            $goods->is_new = $is_new;
            $goods->is_hot = $is_hot;
            $goods->is_recommend = $is_recommend;
            $goods->is_onshelf = $is_onshelf;
            $goods->save();
        }

        $insert_data = [];
        foreach ($attr_values as $v){
            $insert_data[] = [
                'goods_id' => $goods->id ?? $id,
                'attr_name' => $v['attr_name'],
                'attr_value' => $v['attr_value'],
                'updated_at' => date('Y-m-d H:i:s'),
                'created_at' => date('Y-m-d H:i:s')
            ];
        }
        DB::table('goods_attr_value')->insert($insert_data);

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function del(Request $request){
        $id = $request->filled('id') ? $request->id : null;

        if(!$id)
            return json_encode([
                'code' => 0,
                'msg' => 'id can not be null'
            ]);

        $id_arr = explode(',', $id);
        foreach($id_arr as $v){
            //删除
            Goods::destroy($v);
            //删除所有关联属性的值
            GoodsAttrValue::where('goods_id', $v)->delete();
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function uploadImg(Request $request){
        if($request->hasFile('album')){
            $img_url = [];
            foreach ($request->file('album') as $img){
                if($img->isValid()){
                    $img_url[] = QclouduUpload(md5(uniqid(md5(microtime(true)),true)), $img->getRealPath());
                }
            }
            return json_encode([
                'code' => 1,
                'msg' => 'success',
                'img_url' => $img_url
            ]);
        }else{
            return json_encode([
                'code' => 0,
                'msg' => '请上传图片！或检查服务器是否能接收到图片文件'
            ]);
        }
    }

    public function uploadLogo(Request $request){
        if($request->hasFile('upload_logo') && $request->file('upload_logo')->isValid()) {
            $img_url = QclouduUpload(md5(uniqid(md5(microtime(true)), true)), $request->file('upload_logo')->getRealPath());
            return json_encode([
                'code' => 1,
                'msg' => 'success',
                'img_url' => $img_url
            ]);
        }else{
            return json_encode([
                'code' => 0,
                'msg' => 'upload error,please try again'
            ]);
        }
    }

    public function randomKey($length){
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key = '';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,61)};    //生成php随机数
        }
        return $key;
    }

    //=====================================
    //          [API  Function]
    //=====================================

    public function miniappPay(Request $request){
        $openid = $request->filled('openid') ? $request->openid : '';
        $body = $request->filled('body') ? $request->body : '';
        $detail = $request->filled('detail') ? $request->detail : '';
        if(!$openid || !$body){
            return json_encode([
                'code' => -1,
                'msg' => '缺失参数：openid 或者 body'
            ]);
        }
        // 小程序支付
        $order = [
            'out_trade_no' => md5(time().uniqid().$openid),
            'body' => $body,
            'detail' => $detail,
            'total_fee' => '1',//单位：分
            'openid' => $openid,
            'notify_url' => Config('app')['url'] . 'Goods/payNotify'
        ];

        return $this->wechat->miniappPay($order);
    }

    //支付通知
    public function miniappPayNotify(Request $request){
        try{
            $data = json_decode($this->wechat->verify(),true); // 是的，验签就这么简单
            $this->wechat->Message_payment_success(
                $data['openid'],
                $data['out_trade_no'],
                '测试商品',
                number_format($data['total_fee']/100,2),
                date('Y-m-d H:i:s',time())
            );
        } catch (Exception $e) {
            Log::debug($e);
        }

    }

    public function info(Request $request){
        $id = $request->route('id');
        $info = Article::where('article.id',$id)
            ->select(
                'article.id as id',
                'article.thumbnail as thumbnail',
                'article.title as title',
                'article.keywords as keywords',
                'article.cat_id as cat_id',
                'article_category.name as cat_name',
                'article.created_at as created_at',
                'article.content as content',
                'article.author as author'
            )
            ->leftJoin('article_category', 'article.cat_id', '=', 'article_category.id')
            ->first();
        return json_encode([
            'code' => 1,
            'data' => $info
        ]);
    }

    public function getListByCat(Request $request){
        $cat_id = $request->route('cat_id');

        $list = Article::where('article.cat_id',$cat_id)
            ->select(
                'article.id as id',
                'article.thumbnail as thumbnail',
                'article.title as title',
                'article.keywords as keywords',
                'article.cat_id as cat_id',
                'article_category.name as cat_name',
                'article.created_at as created_at',
                //'article.content as content',
                'article.author as author'
            )
            ->leftJoin('article_category', 'article.cat_id', '=', 'article_category.id')
            ->orderBy('article.sort','asc')
            ->orderBy('article.created_at','desc')
            ->get();

        return json_encode([
            'code' => 1,
            'data' => $list
        ]);

    }
}
